package com.meichuang.meipian.video;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.view.View;

import com.example.myapplication.R;
import com.meichuang.meipian.video.log.LogUtil;
import com.meichuang.meipian.video.music.MusicUtil;
import com.meichuang.meipian.video.nativejni.VideoNative;
import com.meichuang.meipian.video.util.AudioTrackManager;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Serializable;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

public class DrawDemoActivity extends AppCompatActivity {

    GLSurfaceView glview;
    private String bgMusicPath="";

    Handler mHandler = new Handler();
    private int width;
    private int height;
    private int oldZtime = -1;
    private int oldPlayTime = -1;
    ZZGLRender mRender;
    private int renderModel;
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.make_video);
        glview = (GLSurfaceView)findViewById(R.id.glview);
        checkAndRequestPermission();
        mRender = new ZZGLRender();
        initRender();

        glview.setEGLContextClientVersion(2);
        glview.setRenderer(mRender);



        VideoNative.checkPakege(getApplicationContext());

        initUi();

    }

    private void checkAndRequestPermission() {
        List<String> lackedPermission = new ArrayList<>();
        if (!(checkSelfPermission(Manifest.permission.READ_PHONE_STATE) == PackageManager.PERMISSION_GRANTED)) {
            lackedPermission.add(Manifest.permission.READ_PHONE_STATE);
        }

        if (!(checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)) {
            lackedPermission.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        }

        if (!(checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)) {
            lackedPermission.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }
        if (!(checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)) {
            lackedPermission.add(Manifest.permission.READ_EXTERNAL_STORAGE);
        }
        // 权限都已经有了，那么直接调用SDK
        if (lackedPermission.size() == 0) {

        } else {
            // 请求所缺少的权限，在onRequestPermissionsResult中再看是否获得权限，如果获得权限就可以调用SDK，否则不要调用SDK。
            String[] requestPermissions = new String[lackedPermission.size()];
            lackedPermission.toArray(requestPermissions);
            requestPermissions(requestPermissions, 1024);
        }
    }
    public void distory(){
        MusicUtil.distory();
        mRender.distoryRender();
        AudioTrackManager.stopAudio();
    }
    @Override
    protected void onPause() {
        super.onPause();
        mRender.addRenderEvent(new ZZGLRender.OpenGLRenderEvent() {
            @Override
            public void run() {
                distory();
            }
        });
    }
    //开始播放模板
    private void play(){
        mRender.setUserConfig(null);
    }
    private void stopPlay(){
        mRender.addRenderEvent(new ZZGLRender.OpenGLRenderEvent() {
            @Override
            public void run() {
                distory();
            }
        });
    }

    private void initRender(){
        mRender.setNativeCallBack(new VideoNative.NativeCallBack() {
            @Override
            public void event(int event, final String message) {
                if(event == VideoNative.ENGINE_EVENT_VIDEORENDEREND){
                    mRender.isEnd = true;
                    mRender.addRenderEvent(new ZZGLRender.OpenGLRenderEvent() {
                        @Override
                        public void run() {
                            mRender.distoryRender();
                            LogUtil.i("end distoryRender");
                        }
                    });

                    if(renderModel == ZZGLRender.RENDER_MODEL_RECORD){
                    }else{
                        MusicUtil.distory();
                        LogUtil.i("start renderEndVideoEncode "+message);
                        AudioTrackManager.stopAudio();
                        LogUtil.i("end renderEndVideoEncode  "+message);
                    }


                }else if(event == VideoNative.ENGINE_EVENT_MUSIC_ENCODE_END && renderModel == ZZGLRender.RENDER_MODEL_RECORD){
                    LogUtil.i("start renderEndVideoEncode "+message);
                    //renderEndVideoEncode(message);
                    LogUtil.i("end renderEndVideoEncode  "+message);
                }else if(event == VideoNative.ENGINE_EVENT_MUSIC_ENCODE_END && renderModel == ZZGLRender.RENDER_MODEL_RENDER){

                }

            }
            @Override
            public  String getScanJson(String id){
                return "";//UiAndEngineCenter.this.getScanJson(id);
            }

            @Override
            public void updateRender(int thisFrame){

                if(renderModel == ZZGLRender.RENDER_MODEL_RENDER && !mRender.isEnd){//&& renderFrameCount%1==0
                    while (true){
                        byte data[] = VideoNative.pullPcmData(AudioTrackManager.audioBufSize);
                        if(data.length <= 0){
                            break;
                        }
                        AudioTrackManager.writDate(data);
                    }
                }
            }
        });
        mRender.setFrameRateAndRenderModel(25,renderModel,300);
        if(renderModel == ZZGLRender.RENDER_MODEL_RENDER){
            AudioTrackManager.startAudio();
        }
    }
    private void initUi(){
        findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        findViewById(R.id.playbutton).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                play();

                findViewById(R.id.playbutton).setVisibility(View.GONE);
            }
        });



        findViewById(R.id.next).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mRender.addRenderEvent(new ZZGLRender.OpenGLRenderEvent() {
                    @Override
                    public void run() {
                        mRender.loadSceneGrop();
                    }
                });
            }
        });
    }


    private static final String MultiSceneTemplateROOT =  ZZGLRender.MultiSceneTemplateROOT;
    private static final String MultiSceneSceneROOT = ZZGLRender.MultiSceneSceneROOT;//



}
